#include "widget.h"
#include "ui_widget.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");
    manager = new QNetworkAccessManager(this);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    // 获取输入框的内容
    QUrl url(ui->lineEdit->text());
    ui->lineEdit->clear();
    // 构造Http请求
    QNetworkRequest request(url);
    // 发送Http请求，并接受响应
    QNetworkReply* response = manager->get(request);

    // 利用信号槽处理响应
    connect(response,&QNetworkReply::finished,this,[=](){
        if(response->error() == QNetworkReply::NoError)
        {
            // 响应正确获取到
            QString html = response->readAll();
            ui->plainTextEdit->setPlainText(html);
        }
        else
        {
            // 响应出错
            ui->plainTextEdit->setPlainText(response->errorString());
        }
        // 释放：下一轮事件循环再进行销毁
        response->deleteLater();
    });
}
